// 精确计算工具函数集合

/**
 * 将数字按精度进行四舍五入，避免浮点精度问题
 */
export function toFixedNumber(num, precision = 2) {
  const n = parseFloat(num) || 0;
  const factor = Math.pow(10, precision);
  return Math.round(n * factor) / factor;
}

/** 精确加法 */
export function preciseAdd(a, b, precision = 2) {
  const aNum = parseFloat(a) || 0;
  const bNum = parseFloat(b) || 0;
  return toFixedNumber(aNum + bNum, precision);
}

/** 精确减法 */
export function preciseSubtract(a, b, precision = 2) {
  const aNum = parseFloat(a) || 0;
  const bNum = parseFloat(b) || 0;
  return toFixedNumber(aNum - bNum, precision);
}

/** 精确乘法 */
export function preciseMultiply(a, b, precision = 2) {
  const aNum = parseFloat(a) || 0;
  const bNum = parseFloat(b) || 0;
  return toFixedNumber(aNum * bNum, precision);
}

/** 精确除法（除数为0时返回0） */
export function preciseDivide(a, b, precision = 2) {
  const aNum = parseFloat(a) || 0;
  const bNum = parseFloat(b) || 0;
  if (bNum === 0) return 0;
  return toFixedNumber(aNum / bNum, precision);
}

export default {
  toFixedNumber,
  preciseAdd,
  preciseSubtract,
  preciseMultiply,
  preciseDivide
};


